package cn.cnsy123.blog.application.controller;

import cn.cnsy123.blog.application.constants.CacheRedisConstant;
import cn.cnsy123.blog.application.http.base.BaseResponse;
import cn.cnsy123.blog.application.http.response.CaptchaResponse;
import com.wf.captcha.GifCaptcha;
import com.wf.captcha.base.Captcha;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Controller
public class CheckImageCodeController {

    private static final Logger logger = LoggerFactory.getLogger(CheckImageCodeController.class);



    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @GetMapping(value = "/captcha/checkcode")
    @ResponseBody
    public BaseResponse<CaptchaResponse> imageCheckCode(HttpServletResponse response){

        BaseResponse<CaptchaResponse> baseResponse = new BaseResponse<CaptchaResponse>();
        baseResponse.setCode("0000");
        baseResponse.setMessage("系统请求成功");
        baseResponse.setRequestTime(new Date(System.currentTimeMillis()));

        // 设置请求头为输出图片类型
        response.setContentType("image/gif");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        CaptchaResponse captchaResponse = null;
        try {

            GifCaptcha captcha = new GifCaptcha(130, 48,6);
            captcha.setCharType(Captcha.TYPE_NUM_AND_UPPER);
            String captchaText = captcha.toBase64();
            String captchaContent = captcha.text();

            String cacheKey = UUID.randomUUID().toString();
            String imageCacheKey = new StringBuilder(CacheRedisConstant.IMAGE_CACHE_PREFIX).append(cacheKey).toString();

            stringRedisTemplate.opsForValue().set(imageCacheKey,captchaContent,3L, TimeUnit.MINUTES);

            captchaResponse = new CaptchaResponse("0000","验证码写入成功",captchaText,cacheKey);

            logger.info("请求验证码，验证码信息为:{},写入CACHE的key:{}",captchaContent,imageCacheKey);

        }catch (Exception e){
            captchaResponse = new CaptchaResponse("1099","验证码写入异常");
            logger.error("请求验证码异常",e);
        }
        baseResponse.setData(captchaResponse);
        baseResponse.setResponseTime(new Date(System.currentTimeMillis()));
        return  baseResponse;

    }



}
